<template>
  <div v-if="status === '1'" class="extract">
    <div class="extract-main">
      <div class="extract-name">
        <span>{{ finalObj.businessName || "请点击开始抽选!" }}</span>
      </div>
      <div class="btn">
        <el-button type="success" size="large" @click="startExtraction"
          >开始抽选</el-button
        >
        <el-button type="warning" size="large" @click="stopExtraction"
          >结束抽选</el-button
        >
      </div>
    </div>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <span>本次随机抽中{{ finalObj.businessName }}，请确认!</span>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="onCancelResult">取消本次抽选结果</el-button> -->
        <el-button type="primary" @click="onSureResult"
          >确认本次抽选结果</el-button
        >
      </span>
    </el-dialog>
  </div>
  <div v-else-if="status !== '1' && !loading">
    <el-empty
      description="
    此计划还未确认，无法抽选"
    />
  </div>
</template>

<script>
import { getPlanFindById, postExtractAdd } from "./api";
import { getBusinessList } from "../business/api";
import { Loading } from "element-ui";
import { mapGetters } from "vuex";
export default {
  name: "Extract",
  data() {
    return {
      status: null,
      planId: "",
      planName: "",
      loading: false,
      loadingInstance: null,
      business: [],
      finalObj: {
        businessName: "",
      },
      form: {
        planId: "",
        planName: "",
        warehouseName: "",
        warehouseId: "",
        creator: "",
      },
      extractionInterval: null,
      dialogVisible: false,
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  created() {
    this.form.planId = this.$route.query.planId;
    this.form.planName = this.$route.query.planName;
    this.form.warehouseName = this.$route.query.warehouseName;
    this.form.warehouseId = this.$route.query.warehouseId;
    this.form.creator = this.userInfo.userName;
    this.checkPlanExist();
  },
  methods: {
    onCancelResult() {
      this.dialogVisible = false;
      this.finalObj.businessName = "";
    },
    onSureResult() {
      postExtractAdd({
        ...this.finalObj,
        ...this.form,
      })
        .then(({ success, message }) => {
          if (success) {
            this.$message.success(message);
          } else {
            this.$message.error(message);
          }
          this.onCancelResult();
          setTimeout(() => {
            this.$router.push("plan");
          }, 200);
        })
        .catch();
    },
    checkPlanExist() {
      try {
        this.loadingInstance = Loading.service({
          fullscreen: false,
        });
        this.loading = true;
        getPlanFindById({ planId: this.form.planId })
          .then(({ success, message, data }) => {
            if (success) {
              this.status = data.status;
              if (data.status !== "1") {
                this.$message.error("此计划还未确认，无法抽选");
              } else {
                this.getBusinessData();
              }
            } else {
              this.$message.error(message);
            }
          })
          .catch();
      } catch (error) {
      } finally {
        this.$nextTick(() => {
          this.loading = false;
          setTimeout(() => {
            this.loadingInstance.close();
          }, 200);
        });
      }
    },
    getBusinessData() {
      getBusinessList({
        page: 1,
        limit: 99999,
        warehouseName: this.form.warehouseName,
      })
        .then((result) => {
          this.business = result.data.map((item) => {
            item.probability = 20;
            return item;
          });
        })
        .catch((err) => {});
    },
    getRandomBusiness() {
      const weightedbusinessList = [];
      this.business.forEach((business) => {
        for (let i = 0; i < business.probability; i++) {
          weightedbusinessList.push({
            businessName: business.businessName,
            businessId: business.businessId,
          });
        }
      });
      const randomIndex = Math.floor(
        Math.random() * weightedbusinessList.length
      );
      return weightedbusinessList[randomIndex];
    },
    startExtraction() {
      const _this = this;
      if (this.extractionInterval) {
        clearInterval(this.extractionInterval);
      }
      // 设置20秒后自动结束
      // this.extractionTimeout = setTimeout(() => {
      //   _this.stopExtraction();
      // }, 10000); // 20秒

      this.extractionInterval = setInterval(() => {
        _this.finalObj = _this.getRandomBusiness();
      }, 32);
    },
    stopExtraction() {
      if (this.extractionInterval) {
        clearInterval(this.extractionInterval);
        setTimeout(() => {
          this.dialogVisible = true;
        }, 500);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.extract {
  width: 100%;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("~@/assets/img/BG_16.jpg") no-repeat center;
  background-size: 100% 100%;
  height: 100vh;
  .extract-main {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 80%;
    height: 50%;
    .extract-name {
      color: #fff;
      margin-bottom: 100px;
      font-size: 30px;
    }

    .btn {
      .el-button {
        width: 250px;
        font-size: 20px;
        letter-spacing: 16px;
        font-weight: bold;
        cursor: pointer;
      }
    }
  }
}
</style>
